﻿#region MIT
/*
Engine Of Evermore (http://code.google.com/p/engineofevermore/)
Copyright (c) 2008, 2009 Michael Woerister

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EngineOfEvermore.Scene;
using System.Diagnostics;
using System.ComponentModel;
using EngineOfEvermore.Common;
using Platinum.PropertyEditors;
using Platinum.Validators;
using Platinum;
using EngineOfEvermore.Editor.Common.Command;


namespace EngineOfEvermore.Editor.SceneEditor.PropertyEditor
{
    /// <summary>
    /// This class facilitates a binding between a SceneObject and the PropertyEditor in both
    /// directions.
    /// </summary>
    class SceneObjectBinding : IDisposable
    {
        private Editor.Common.Controls.PropertyEditors.Vector2dEditor _positionEditor;
        private ValidatingStringEditor _rotationEditor;
        private Editor.Common.Controls.PropertyEditors.Vector2dEditor _velocityEditor;
        private ValidatingStringEditor _spaceEditor;
        private IPropertyGridSection _sceneObjectGridSection;
        private ICommandStack _commandStack;
        
        private PropertyBinding _positionBinding;
        private PropertyBinding _rotationBinding;
        private PropertyBinding _velocityBinding;
        private PropertyBinding _spaceBinding;

        private List<IComponentBinding> _componentBindings = new List<IComponentBinding>();

        public SceneObject SceneObject { get; private set; }
        public PropertyGrid PropertyGrid { get; private set; }

        public SceneObjectBinding( SceneObject sceneObject, PropertyGrid propertyGrid,
            ICommandStack commandStack )
        {
            Debug.Assert( sceneObject != null );
            Debug.Assert( propertyGrid != null );
            Debug.Assert( commandStack != null );

            this.SceneObject = sceneObject;
            this.PropertyGrid = propertyGrid;

            _commandStack = commandStack;
            
            _createSceneObjectSection();
            _createComponentSections();
        }

        private void _createComponentSections()
        {
            for ( int i = 0; i < this.SceneObject.ComponentCount; ++i )
            { 
                var component = this.SceneObject.GetComponent( i );
                var attributes = TypeDescriptor.GetAttributes( component ).Cast<Attribute>();

                if ( attributes.Any( a => a is PerTypeAttribute ) )
                    continue;

                if ( attributes.Any( a => a is BrowsableAttribute
                    && !( (BrowsableAttribute) a ).Browsable ) )
                    continue;

                _componentBindings.Add( ComponentBindingFactory.Create( component, 
                    this.PropertyGrid, _commandStack ) );
            }
        }

        private Platinum.BoundPropertyDescriptor _getPropertyDescriptor( String propertyName )
        {
            var pd = new BoundPropertyDescriptor();

            pd.PropertyDescriptor = TypeDescriptor.GetProperties( this.SceneObject )
                .Find( propertyName, false );

            Debug.Assert( pd.PropertyDescriptor != null );

            pd.PropertyOwner = this.SceneObject;

            return pd;
        }

        private void _createSceneObjectSection()
        {
            _sceneObjectGridSection = this.PropertyGrid.Items.Add( "SceneObject" );

            _bindPositionProperty();
            _bindRotationProperty();
            _bindVelocityProperty();
            _bindSpaceProperty();
        }

        private void _bindPositionProperty()
        {
            var propertyDescriptor = _getPropertyDescriptor( "Position" );

            Debug.Assert( propertyDescriptor.PropertyDescriptor.Attributes
                .OfType<PerInstanceAttribute>().Any() );

            _positionEditor = new Common.Controls.PropertyEditors.Vector2dEditor();
            _sceneObjectGridSection.Items.Add( "Position", _positionEditor );
            _positionEditor.PropertyDescriptor = propertyDescriptor;
            
            var eventAdapter = ActionAdapterFactory.Create( this.SceneObject, "PositionChanged" );

            _positionBinding = new PropertyBinding( eventAdapter, propertyDescriptor, 
                _positionEditor, _commandStack );
        }

        private void _bindRotationProperty()
        {
            var propertyDescriptor = _getPropertyDescriptor( "Rotation" );

            Debug.Assert( propertyDescriptor.PropertyDescriptor.Attributes
                .OfType<PerInstanceAttribute>().Any() );

            _rotationEditor = new ValidatingStringEditor();
            _rotationEditor.Validator = DefaultValidator.CreateFor( typeof( float ) );
            _sceneObjectGridSection.Items.Add( "Rotation", _rotationEditor );

            _rotationEditor.PropertyDescriptor = propertyDescriptor;
            
            
            var eventAdapter = ActionAdapterFactory.Create( this.SceneObject, "RotationChanged" );

            _rotationBinding = new PropertyBinding( eventAdapter, propertyDescriptor,
                _rotationEditor, _commandStack );
        }

        private void _bindVelocityProperty()
        {
            var propertyDescriptor = _getPropertyDescriptor( "LinearVelocity" );

            Debug.Assert( propertyDescriptor.PropertyDescriptor.Attributes
                .OfType<PerInstanceAttribute>().Any() );

            _velocityEditor = new Common.Controls.PropertyEditors.Vector2dEditor();
            _sceneObjectGridSection.Items.Add( "LinearVelocity", _velocityEditor );

            _velocityEditor.PropertyDescriptor = propertyDescriptor;
            
            var eventAdapter = ActionAdapterFactory.Create( this.SceneObject, 
                "LinearVelocityChanged" );

            _velocityBinding = new PropertyBinding( eventAdapter, propertyDescriptor,
                _velocityEditor, _commandStack );
        }

        private void _bindSpaceProperty()
        {
            var propertyDescriptor = _getPropertyDescriptor( "Space" );

            Debug.Assert( propertyDescriptor.PropertyDescriptor.Attributes
                .OfType<PerInstanceAttribute>().Any() );

            _spaceEditor = new ValidatingStringEditor();
            _spaceEditor.Validator = new RangedValueValidator<int>( 0, int.MaxValue );
            _sceneObjectGridSection.Items.Add( "Space", _spaceEditor );

            _spaceEditor.PropertyDescriptor = propertyDescriptor;
            
            var eventAdapter = ActionAdapterFactory.Create( this.SceneObject, "SpaceChanged" );

            _spaceBinding = new PropertyBinding( eventAdapter, propertyDescriptor,
                _spaceEditor, _commandStack );
        }

        private void _unsubscribeEvents()
        {
            _positionBinding.Dispose();
            _rotationBinding.Dispose();
            _velocityBinding.Dispose();
            _spaceBinding.Dispose();
        }
        
        public void Dispose()
        {
            _unsubscribeEvents();

            foreach ( var componentBinding in _componentBindings )
            {
                componentBinding.Dispose();
            }

            _componentBindings.Clear();

            this.SceneObject = null;
            this.PropertyGrid = null;
            
            _commandStack = null;
            _positionEditor = null;
            _rotationEditor = null;
            _velocityEditor = null;
            _spaceEditor = null;
        }
    }

    #if ENGINE_OF_EVERMORE_ENABLE_UNIT_TESTS
    namespace Test
    {
        using NUnit.Framework;

        [TestFixture]
        public class SceneObjectBindingFixture
        {
            [Test]
            public void TestCreation() 
            {
                Platinum.PropertyGrid pGrid = new Platinum.PropertyGrid();
                SceneObject sceneObject = new SceneObject();
                var commandStack = new MockCommandStack();

                SceneObjectBinding binding = new SceneObjectBinding( sceneObject, pGrid, 
                    commandStack );

                Assert.That( binding.SceneObject, Is.SameAs( sceneObject ) );
                Assert.That( binding.PropertyGrid, Is.SameAs( pGrid ) );
            }

            [Test]
            public void TestThatGridHasSceneObjectSection()
            {
                Platinum.PropertyGrid pg = new Platinum.PropertyGrid();
                SceneObject sceneObject = new SceneObject();
                var commandStack = new MockCommandStack();

                new SceneObjectBinding( sceneObject, pg, commandStack );

                Assert.That( pg.Items["SceneObject"], Is.Not.Null );
            }

            [Test]
            public void TestThatSceneObjectSectionContainsPositionRotationVelocityAndScale()
            {
                Platinum.PropertyGrid pg = new Platinum.PropertyGrid();
                SceneObject sceneObject = new SceneObject();
                var commandStack = new MockCommandStack();

                new SceneObjectBinding( sceneObject, pg, commandStack );

                var sceneObjectSection = pg.Items["SceneObject"];

                Assert.That( sceneObjectSection.Items["Position"], Is.Not.Null );
                Assert.That( sceneObjectSection.Items["Rotation"], Is.Not.Null );
                Assert.That( sceneObjectSection.Items["LinearVelocity"], Is.Not.Null );
                Assert.That( sceneObjectSection.Items["Space"], Is.Not.Null );
            }

            [Test]
            public void TestIfBindingsAreCorrectInEditor()
            {
                Platinum.PropertyGrid pg = new Platinum.PropertyGrid();
                SceneObject sceneObject = new SceneObject();
                var commandStack = new MockCommandStack();

                new SceneObjectBinding( sceneObject, pg, commandStack );

                var section = pg.Items["SceneObject"];

                Assert.That( _isSceneObjectPropertyBoundTo( "Position", sceneObject, section ) );
                Assert.That( _isSceneObjectPropertyBoundTo( "Rotation", sceneObject, section ) );
                Assert.That( _isSceneObjectPropertyBoundTo( "LinearVelocity", sceneObject, 
                    section ) );
                Assert.That( _isSceneObjectPropertyBoundTo( "Space", sceneObject, section ) );
            }

            

            bool _isSceneObjectPropertyBoundTo( String propertyName, SceneObject sceneObject,
                Platinum.IPropertyGridSection gridSection )
            {
                var positionItem = gridSection.Items[propertyName];
                var editor = positionItem.PropertyEditor;
                var pd = editor.PropertyDescriptor;

                var expectedPD = TypeDescriptor.GetProperties( sceneObject )
                    .Find( propertyName, false );

                return pd.PropertyDescriptor.Equals( expectedPD );
            }
        }
    }
    #endif
}
